package com.lmf.rabbitmq.config;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 *  高级确认发布，添加配置类：
 *  备份交换机：
 */
@Configuration
public class ConfirmConfig {

    //确认交换机
    public static final String CONFIRM_EXCHANGE_NAME = "confirm.exchange";
    //确认队列
    public static final String CONFIRM_QUEUE_NAME = "confirm.queue";
    //备份交换机
    public static final String BACKUP_EXCHANGE_NAME = "backup.exchange";
    //备份队列
    public static final String BACKUP_QUEUE_NAME = "backup.queue";
    //警告队列
    public static final String WARNING_QUEUE_NAME = "warning.queue";

    //声明业务 Exchange
    @Bean("confirmExchange")
    public DirectExchange confirmExchange() {
        Map<String, Object> arguments = new HashMap<>();
        //设置该交换机的备份交换机，
        // 注意：备份交换机比消息回退机制优先级高
        arguments.put("alternate-exchange",BACKUP_EXCHANGE_NAME);
        return ExchangeBuilder.directExchange(CONFIRM_EXCHANGE_NAME).withArguments(arguments).durable(true).build();
    }

    // 声明确认队列
    @Bean("confirmQueue")
    public Queue confirmQueue() {
        return QueueBuilder.durable(CONFIRM_QUEUE_NAME).build();
    }

    // 声明确认队列绑定关系
    @Bean
    public Binding queueBinding(@Qualifier("confirmQueue") Queue queue,
                                @Qualifier("confirmExchange") DirectExchange exchange) {
        return BindingBuilder.bind(queue).to(exchange).with("key1");
    }

    /*-------------------------------------------备份交换机如下：------------------------------------------------*/

    //声明备份交换机
    @Bean("backupExchange")
    public FanoutExchange backupFanoutExchange(){
        return ExchangeBuilder.fanoutExchange(BACKUP_EXCHANGE_NAME).build();
    }

    //声明备份队列
    @Bean("backupQueue")
    public Queue queueBackup(){
        return QueueBuilder.durable(BACKUP_QUEUE_NAME).build();
    }

    //绑定备份队列与备份交换机
    @Bean
    public Binding queueBackupBindingExchange(@Qualifier("backupQueue") Queue queue,
                                            @Qualifier("backupExchange") FanoutExchange exchange){
        return BindingBuilder.bind(queue).to(exchange);
    }

    //声明警告队列
    @Bean("warningQueue")
    public Queue queueWarn(){
        return QueueBuilder.durable(WARNING_QUEUE_NAME).build();
    }


    //绑定警告队列与备份交换机
    @Bean
    public Binding queueWarnBindingExchange(@Qualifier("warningQueue") Queue queue,
                                            @Qualifier("backupExchange") FanoutExchange exchange){
        return BindingBuilder.bind(queue).to(exchange);
    }

}
